package org.example.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author: ZhuYouBin
 * @date: 2022/4/7 16:26
 * @description:
 */
public class AccessPrivateDemo {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException,
            InstantiationException, IllegalAccessException,
            NoSuchMethodException, InvocationTargetException {
        // 1、创建Class类对象
        Class<?> clazz = Class.forName("org.example.reflection.Student");
        // 2、创建对象
        Student student = (Student) clazz.newInstance();
        // 3、获取私有方法
        Method method = clazz.getDeclaredMethod("subTest01", null);
        // 解除安全性检查
        method.setAccessible(true);
        // 调用方法
        Object ret = method.invoke(student, null);
        System.out.println("方法返回值：" + ret);
    }
    static void test01() throws ClassNotFoundException, NoSuchFieldException,
            InstantiationException, IllegalAccessException {
        // 1、创建Class类对象
        Class<?> clazz = Class.forName("org.example.reflection.Student");
        // 2、创建对象
        Student student = (Student) clazz.newInstance();
        // 3、获取私有属性
        Field field = clazz.getDeclaredField("stuPriVal");
        // 解除安全性检查
        field.setAccessible(true); // true表示解除安全性检查
        // 给私有属性重新赋值
        field.set(student, "私有属性赋值新值");
        System.out.println("赋值后的值：" + field.get(student));
    }
}
